import deepClone from '@/libs/deepClone'
import cecharts, {ECOption} from '@/libs/global/echarts'
import {PropType} from 'vue'

export type SetOption = (data: ECOption) => void

const CEcharts = defineComponent({
  props: {
    id: {
      type: String,
      required: true
    },
    width: {
      type: String,
      required: true
    },
    height: {
      type: String,
      required: true
    },
    option: {
      type: Object as PropType<ECOption>
    },
    lazy: {
      type: Boolean,
      default: false
    },
    beforeInit: Function as PropType<(ec: typeof cecharts) => void>
  },
  emits: {
    // initEc: (ec: echarts.ECharts, setOption: SetOption, registerChinaMap: (data: any) => void): boolean => true
    // eslint-disable-next-line @typescript-eslint/no-unused-vars, @typescript-eslint/ban-types
    initEc: (ec: cecharts.ECharts, setOption: Function): boolean => true
  },
  setup(props, {emit}) {
    let ec: cecharts.ECharts | null = null
    const initTimer = ref<NodeJS.Timer | undefined>(undefined)

    watch(
      () => props.option,
      n => {
        if (props.lazy) {
          return
        }

        if (initTimer.value !== undefined) {
          clearInterval(initTimer.value as unknown as number)
        }

        const timer = setInterval(() => {
          if (ec) {
            n && setOption(deepClone(n))
            clearInterval(timer)
          } else {
            getEc()
          }
        }, 500)
        initTimer.value = timer
      },
      {deep: true, immediate: true}
    )

    function getEc() {
      const dom = document.getElementById(props.id)
      window.removeEventListener('resize', resizeEchart)
      if (dom) {
        props.beforeInit && props.beforeInit(cecharts)

        ec = cecharts.init(dom, undefined, {locale: 'ZH'})

        window.addEventListener('resize', resizeEchart)

        emit('initEc', ec, setOption)
      }
    }

    function setOption(option: ECOption, idx = 0) {
      if (idx === 10) {
        console.log('渲染次数超过限制', props.id)
        return
      }
      if (ec) {
        ec.clear()
        console.log('渲染开始了', props.id, option)
        ec.showLoading({text: '加载中...'})
        setTimeout(() => {
          console.log('渲染结束了', props.id)
          ec?.hideLoading()
        }, 2000)
        ec.setOption(option)
      } else {
        getEc()
        setOption(option, idx + 1)
      }
    }

    function resizeEchart() {
      ec && ec.resize()
    }

    onMounted(() => {
      getEc()
    })

    return () => (
      <div
        class='inline-block'
        id={props.id}
        style={{
          width: props.width,
          height: props.height
        }}
      ></div>
    )
  }
})

export default CEcharts
